package com.foreveross.taskservice.application.impl.task.mq;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.pool.PooledConnection;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;

import com.foreveross.taskservice.application.task.mq.ITaskToMQApplication;
import com.foreveross.taskservice.common.CacheDataSpace;
import com.foreveross.taskservice.common.model.AbstractTaskModel;
import com.foreveross.taskservice.common.mq.destination.DestinationFactory;
import com.foreveross.taskservice.infra.util.DateUtil;
@Service
public class TaskToMQApplicationImpl implements ITaskToMQApplication{
	@Resource(name="sendJmsTemplate")
	private JmsTemplate jmsTemplate;
	@Override
	public void sendTasks(List<AbstractTaskModel> tasks) throws Exception {
		for( AbstractTaskModel t:tasks){
			jmsTemplate.setPriority(t.getPriority());
			jmsTemplate.convertAndSend(DestinationFactory.getInstance().getChannelDestination(
					new CacheDataSpace(t.getTaskType()),t.getChannel().getHbaseKey()), t);
		}
	}
	@Override
	public void clearHistory() throws Exception {
			PooledConnection conn = (PooledConnection)jmsTemplate.getConnectionFactory().createConnection();
			ActiveMQConnection amqConn = conn.getConnection();
			//销毁所有的队列
			//获得昨天的日期
			String yesterdate = DateUtil.formatDay(org.dayatang.utils.DateUtils.getPrevDay(new Date()), "yyyyMMdd");
			for( String key : DestinationFactory.getInstance().getAllDestination().keySet()){
				if(key.indexOf(yesterdate) > -1){
					try{
						amqConn.destroyDestination((ActiveMQDestination)(DestinationFactory.getInstance().getAllDestination().get(key)));
					}catch(Exception e){
						e.printStackTrace();
					}
					DestinationFactory.getInstance().remove(key);
				}
			}
			
	}

	
}
